//
//  CitySearchViewController.m
//  search
//
//  Created by 蔡万鸿 on 15/7/11.
//  Copyright (c) 2015年 黄花菜. All rights reserved.
//

#import "CitySearchViewController.h"
#import "CityModel.h"
#import "MJExtension.h"

@interface CitySearchViewController ()
/** 城市的总数据*/
@property (nonatomic, strong) NSArray *cities;

/** 检索结果数组*/
@property (nonatomic, strong) NSMutableArray *resultData;
@end

@implementation CitySearchViewController

- (NSArray *)cities {
    
    if (_cities == nil) {
        _cities = [CityModel objectArrayWithFilename:@"cities.plist"];
    }
    return _cities;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.resultData = [NSMutableArray array];
}

#pragma mark 重写set 进行数据检索
- (void)setSearchText:(NSString *)searchText
{
    //1. copy
    _searchText = [searchText copy];
    
    //2. 转换小写
    searchText = searchText.lowercaseString;
    
    //3. 清空
    [self.resultData removeAllObjects];
    
    //4. 检索
    for (CityModel *cityModel in self.cities) {
        if ([cityModel.name containsString:searchText] || [cityModel.pinYin containsString:searchText] || [cityModel.pinYinHead containsString:searchText]) {
            // 把城市的名字加入数组
            [self.resultData addObject:cityModel.name];
        }
    }
    
    //5. 刷新
    [self.tableView reloadData];
}

#pragma mark - 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.resultData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    
    cell.textLabel.text = self.resultData[indexPath.row];
    
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [NSString stringWithFormat:@"共有%lu个搜索结果",(unsigned long)self.resultData.count];
}
@end
